<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row>
        <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      </el-row>
      <el-row>
        <!--步骤条-->
        <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
      </el-row>
      <el-form :model="addGoodsForm" :rules="addGoodsFormRules"
               ref="addGoodsFormRef" label-width="100px" label-position="top">
        <el-tabs v-model="activeIndex" :tab-position="'left'"
                 :before-leave="beforeTabsLeave" @tab-click="tabsClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!--级联选择器，props用来指定选中对象-->
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cateList"
                :props="{ expandTrigger: 'hover',value:cascadeProps.value,label:cascadeProps.label,children:cascadeProps.children }"
                @change="handleChange"
                style="width: 30%"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="(item,index) in manyTableData" :label="item.attr_name" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(item1,index1) in item.attr_vals"
                  :label="item1"
                  :key="index1"
                  border
                  size="mini"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!--action图片要上传到的后台API地址-->
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce"/>
            <el-button type="primary" style="margin-top: 15px" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!--图片预览-->
    <el-dialog title="图片预览" :visible.sync="previewVisibleDialog" width="50%">
      <img :src="previewPath" width="100%">
    </el-dialog>
  </div>
</template>

<script>
  import _ from "lodash"
  export default {
    name: "Add",
    data() {
      return {
        //步骤条步骤数
        activeIndex: "0",
        //表单绑定数据
        addGoodsForm:{
          goods_name:"",
          goods_price:0,
          goods_weight:0,
          goods_number:0,
          //商品分类级联框被选中分类的数组id
          goods_cat:[],
          //图片的数组
          pics:[],
          //商品的详情
          goods_introduce:"",
          //商品的参数和属性
          attrs:[]
        },
        //商品分类数据
        cateList:[],
        //指定级联选择器配置对象
        cascadeProps:{
          value:"cat_id",
          label:"cat_name",
          children:"children"
        },
        //商品参数列表
        manyTableData:[],
        //商品属性列表
        onlyTableData:[],
        //上传图片的url地址
        uploadURL:"http://localhost:8888/api/private/v1/upload",
        previewPath:"",
        //图片预览框是否显示
        previewVisibleDialog:false,
        //图片上传组件的headers请求头对象
        headerObj:{
          Authorization:window.sessionStorage.getItem("token")
        },
        //表单绑定规则
        addGoodsFormRules:{
          goods_name:[{ required: true, message: '请输入商品名称', trigger: 'blur' }],
          goods_price:[{ required: true, message: '请输入商品价格', trigger: 'blur' }],
          goods_weight:[{ required: true, message: '请输入商品重量', trigger: 'blur' }],
          goods_number:[{ required: true, message: '请输入商品数量', trigger: 'blur' }],
          goods_cat:[{ required: true, message: '请输入商品分类', trigger: 'blur' }],
        }
      }
    },
    created() {
      this.getCateList();
    },
    methods:{
      //获取商品分类数据
      async getCateList(){
        const result=(await this.$http.get("categories")).data;
        if(result.meta.status!==200) this.$message.error("获取商品分类失败");
        this.cateList=result.data;
      },
      //级联选中项发生变化
      handleChange(){
        if(this.addGoodsForm.goods_cat.length!==3){
          this.addGoodsForm.goods_cat=[];
        }
      },
      beforeTabsLeave(activeName,oldActiveName){
        if(oldActiveName==="0"&&this.addGoodsForm.goods_cat.length!==3) {
          this.$message.error("请先选择商品分类");
          return false;
        }
      },
      async tabsClicked(){
        if(this.activeIndex==="1"){
          const result=(await this.$http.get("categories/" + this.cateId + "/attributes", {params: {sel: "many"}})).data;
          if(result.meta.status!==200) return this.$message.error("请求商品参数失败");
          this.manyTableData=result.data;
          result.data.forEach(item=>{
            item.attr_vals=item.attr_vals.length===0?[]:item.attr_vals.split(" ");
          })
        }
        else if(this.activeIndex==="2"){
          const result=(await this.$http.get("categories/" + this.cateId + "/attributes", {params: {sel: "only"}})).data;
          if(result.meta.status!==200) return this.$message.error("请求商品属性失败");
          this.onlyTableData=result.data;
        }
      },
      //处理预览图片
      handlePreview(file){
        this.previewPath=file.response.data.url;
        this.previewVisibleDialog=true;
      },
      //处理移除图片
      handleRemove(file){
        const filePath=file.response.data.tmp_path;
        const i=this.addGoodsForm.pics.findIndex(x=>{
          x.pic === filePath
        })
        this.addGoodsForm.pics.splice(i,1);
      },
      //监听图片上传成功
      handleSuccess(response){
        const picInfo={pic:response.data.tmp_path};
        this.addGoodsForm.pics.push(picInfo);
      },
      //添加商品
      add(){
        this.$refs.addGoodsFormRef.validate(async valid=>{
          if(!valid) return this.$message.error("请填写必要的表单项");
          //执行添加的业务逻辑
          //深拷贝lodash cloneDeep(Obj)
          const form = _.cloneDeep(this.addGoodsForm);
          form.goods_cat=form.goods_cat.join(",");
          //处理动态参数和静态属性
          this.manyTableData.forEach(item=>{
            const newInfo={attr_id:item.attr_id,attr_vals:item.attr_vals.join(" ")};
            this.addGoodsForm.attrs.push(newInfo);
          })
          this.onlyTableData.forEach(item=>{
            const newInfo={attr_id:item.attr_id,attr_vals:item.attr_vals};
            this.addGoodsForm.attrs.push(newInfo);
          })
          form.attrs=this.addGoodsForm.attrs;
          //商品的名称必须是唯一的
          const result=(await this.$http.post("goods", form)).data;
          if(result.meta.status!==201) return this.$message.error("添加商品失败");
          this.$message.success("添加商品成功");
          this.$router.push("/home/goods");
        })
      }
    },
    computed:{
      cateId(){
        if(this.addGoodsForm.goods_cat.length===3){
          return this.addGoodsForm.goods_cat[2];
        }
        return null;
      }
    }
  }
</script>

<style scoped lang="less">
  .el-checkbox{
    margin: 0 10px 0 0 !important;
  }
</style>
